<?php

namespace Admin\Controller;

class BillController extends CommonController {

    /**
     * 初始化
     */
    public function _initialize() {

    }

    /**
     * 订单列表
     */
    public function index() {
        $this->assign('pages', 3);
        $this->assign('door', 1);
        $this->display();
    }

    /**
     * 订单明细
     */
    public function detail() {
        $idStr = session('departStr');
        $where = " order_sn > 99999999 and order_info.depart_id in ($idStr)";
        $counts = D('Home/OrderDetail')->where($where)->count();
        $pages = $counts % C('ADMIN_PAGES') == 0 ? $counts / C('ADMIN_PAGES') : floor($counts / C('ADMIN_PAGES')) + 1;
        $door = M("user_depart")->where(" depart_id in ($idStr)")->select();
        $this->assign('door', $door);
        $this->assign('pages', $pages);
        $this->display();
    }

    /**
     * 鼠标查看
     */
    public function mouseView() {
        $id = I('get.id', 0, 'intval');
        $list = D('Home/OrderDetail')->where("order_goods.order_id = $id")->select();
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 订单发货
     */
    public function send() {
        $id = I('post.id', 0, 'intval');
        $ret = \Com\Order::addDeliveryOrder($id);
        if ($ret) {
            $this->ajaxSuccess("发货单生成成功");
        } else {
            $this->ajaxError("发货单生成失败");
        }
    }

    /**
     * 取消订单
     */
    public function cancel() {
        $id = I('post.id', 0, 'intval');
        $info = M('order_info')->where("order_id = $id")->find();
        if ($info['order_status'] == 2) {
            $this->ajaxError("已取消订单无法再次取消");
        }
        if ($info['shipping_status'] == 2) {
            $this->ajaxError("确认收货订单，无法取消，请先退货！");
        }
        if ($info['shipping_status'] == 1) {
            $this->ajaxError("已发货订单，无法取消，请先取消发货！");
        }
        if ($info['shipping_status'] == 5) {
            $this->ajaxError("发货中，无法取消，请先删除发货单！");
        }
        if ($info['shipping_status'] == 4) {
            $this->ajaxError("部分发货，无法取消，请取消部分发货");
        }
        if ($info['is_distributor'] == 1) {
            // 取消佣金操作
            $dis = new \Com\Dis($id);
            $dis->sellBackCancel();
        }
        $order = \Com\Order::initOrder();
        $order->cancelOrder($id);
        $this->ajaxSuccess("订单取消成功");
    }

    public function cancelProfit() {
        $id = I('post.id', 0, 'intval');
        $info = M('order_info')->where("order_id = $id and distribute_status =1")->find();
        if (empty($info)) {
            $this->ajaxError("订单未分佣");
        } else {
            $dis = new \Com\Dis($id);
            $dis->sellBackCancel();
            $this->ajaxSuccess("佣金取消成功");
        }
    }

    public function giveProfit() {
        $id = I('post.id', 0, 'intval');
        $info = M('order_info')->where("order_id = $id and distribute_status =0 and pay_status = 2")->find();
        if (empty($info)) {
            $this->ajaxError("订单未付款或已经分用过！");
        } else {
            $dis = new \Com\Dis($id);
            $dis->sellBack();
            $this->ajaxSuccess("佣金发放成功");
        }
    }

    /**
     * 查看详情
     */
    public function view() {
        $id = I('get.id', 0, 'intval');
        $list = D('Home/OrderDetail')->where("order_goods.order_id = $id")->select();
        $info = $list[0];
        $log = M('order_action')->where("order_id = $id")->select();
        //$sendList = D('DeliveryDetail')->where("delivery_order.order_id = $id")->select();
        $this->assign('list', $list);
        $this->assign('action', $log);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     *
     * 分页数据
     */
    public function listTable($page = 1) {
        // $idStr = session('departStr');
        $where        = " 1=1 ";
        $apply_number = I('post.apply_number','','string');
        $dinfo        = I('post.d_info','','string');
        $pinfo        = I('post.p_info','','string');
        $stime        = I('post.start_time', '', 'string');
        $etime        = I('post.end_time', '', 'string');
        if(!empty($apply_number) && strlen($apply_number)>5){
            $where .= " and apply_number like '%$apply_number%' ";
        }
        if(!empty($dinfo)){
            if(floatval($dinfo)>0){
                $where .= " and phone_a like '%$dinfo%' ";
            }else{
                $where .= " and real_name like '%$dinfo%' ";
            }
        }
        if(!empty($pinfo)){
            if(floatval($dinfo)>0){
                $where .= " and p_phone like '%$pinfo%' ";
            }else{
                $where .= " and p_name like '%$pinfo%' ";
            }
        }
        if(!empty($stime)){
            $where .= " and apply_time >= '$stime' ";
        }
        if(!empty($etime)){
            $where .= " and apply_time <= '$etime' ";
        }
        $bill      = D('Admin/BillDetailView');
        $list      = $bill->page($page, C('ADMIN_PAGES'))->where($where)->order('id desc')->select();
        $counts    = $bill->where($where)->count();
        $totalPage = $counts % C('ADMIN_PAGES') == 0 ? $counts / C('ADMIN_PAGES') : floor($counts / C('ADMIN_PAGES')) + 1;
        $this->assign('totalPage', $totalPage);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     *
     * 分页数据
     */
    public function listDetailTable($page = 1) {
        $listDetail = D('Home/OrderDetail');
        $idStr = session('departStr');
        $where = " order_sn > 99999999 and order_info.depart_id in ($idStr)";
        $page = I('post.page', 0, 'intval');
        $buytype = I('post.paytype', 2, 'intval');
        $billtype = I('post.billtype', -1, 'intval');
        $order = I('post.order', 'order_id desc', 'string');
        $stime = strtotime(I('post.start_time', '', 'string'));
        $etime = strtotime(I('post.end_time', '', 'string'));
        $orderSn = I('post.order_sn', '', 'string');
        $username = I('post.user_name', 0, 'intval');
        $departId = I('post.sell_depart', 0, 'intval');
        if ($username > 0) {
            $where .= " and user_name = $username ";
        }
        if ($departId > 0 && $departId < 999998) {
            $where .= " and order_info.depart_id = $departId ";
        }
        $buyMan = I('post.buy_name', '', 'string');
        if ($stime > 0) {
            $where .= " and order_info.add_time >= $stime ";
        }
        if ($etime > 0) {
            $where .= " and order_info.add_time <= $etime ";
        }
        if (!empty($orderSn)) {
            $where .= " and order_sn like '%$orderSn%'";
        }
        if (!empty($buyMan)) {
            $where .= " and consignee like '%$buyMan%'  ";
        }
        if ($buytype > 0) {
            if ($buytype == 1) {
                $where .= " and order_status = 0 ";
            }
            if ($buytype == 2) {
                $where .= " and pay_status = 2 ";
            }
            if ($buytype == 3) {
                $where .= " and pay_status = 2 and shipping_status = 1 ";
            }
            if ($buytype == 4) {
                $where .= " and order_status = 2 ";
            }
            if ($buytype == 5) {
                $where .= " and pay_status = 2 and shipping_status in (3,4,5) ";
            }
            if ($buytype == 6) {
                $where .= " and pay_status = 2 and shipping_status = 2 ";
            }
        }
        if ($billtype >= 0) {
            $where .= " and offline_status = $billtype ";
        }
        $list = $listDetail->page($page, C('ADMIN_PAGES'))->order('order_id desc')->where($where)->select();
        $counts = $listDetail->where($where)->count();
        $totalPage = $counts % C('ADMIN_PAGES') == 0 ? $counts / C('ADMIN_PAGES') : floor($counts / C('ADMIN_PAGES')) + 1;
        $this->assign('totalPage', $totalPage);
        $total = $listDetail->where($where)->field('sum(order_goods.goods_number) qty')->find();
        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->display();
    }

    /**
     * 下载数据
     */
    public function downLoad() {
        //$idStr = session('departStr');
        $where        = " 1=1 ";
        $apply_number = I('get.apply_number','','string');
        $dinfo        = I('get.d_info','','string');
        $pinfo        = I('get.p_info','','string');
        $stime        = I('get.start_time', '', 'string');
        $etime        = I('get.end_time', '', 'string');
        if(!empty($apply_number) && strlen($apply_number)>5){
            $where .= " and apply_number like '%$apply_number%' ";
        }
        if(!empty($dinfo)){
            if(floatval($dinfo)>0){
                $where .= " and phone_a like '%$dinfo%' ";
            }else{
                $where .= " and real_name like '%$dinfo%' ";
            }
        }
        if(!empty($pinfo)){
            if(floatval($dinfo)>0){
                $where .= " and p_phone like '%$pinfo%' ";
            }else{
                $where .= " and p_name like '%$pinfo%' ";
            }
        }
        if(!empty($stime)){
            $where .= " and apply_time >= '$stime' ";
        }
        if(!empty($etime)){
            $where .= " and apply_time <= '$etime' ";
        }
        $bill      = D('Admin/BillDetailView');

        $data    = $bill->where($where)->select();
        $counts  = count($data);
        $dataArr = array_chunk($data,2000);
        $fileArr = array();
        $title   = array('apply_number'=>'单号', 'apply_time'=>'申请时间', 'from_place'=>'出发','to_place'=> '目的','p_name'=> '乘客', 'p_phone'=>'乘客手机', 'go_time'=>'出发时间', 'odometer'=>'里程', 'use_time'=>'耗时', 'money'=>'金额', 'license_plate'=>'车牌', 'name'=>'车型', 'real_name'=>'司机', 'phone_a'=>'司机电话','status'=>'订单状态','tag'=>'订单类型');
        foreach($dataArr as $v){
            vendor('csv.CSV');
        	$csv = new \CSV();
        	$csv->open($title);
        	$csv->writeAll($v);
        	$fileArr[] = $csv->myClose();
        }
        $csv->mergeCsvToDownload($fileArr);
    }

    /**
     * 修改订单
     */
    public function changeStatus() {
        if (IS_POST) {
            $userInfo = session('user_info');
            $oid = I('post.order_id', 0, 'intval');
            $where = "order_id = $oid";
            $info = M('order_info')->where($where)->find();
            $data['depart_id'] = I('post.depart_id', 0, 'intval');
            $data['offline_status'] = I('post.offline_status', 0, 'intval');
            $data['staff_id'] = I('post.staff_id', 0, 'intval');
            $data['add_time'] = strtotime(I('post.add_time', '', 'string'));
            $changeDesc = '';
            if ($info['depart_id'] != $data['depart_id']) {
                $changeDesc .= '修改归属店铺[' . $info['depart_id'] . '=>' . $data['depart_id'] . '];';
            }
            if ($info['offline_status'] != $data['offline_status']) {
                $changeDesc .= '修改订单状态[' . $info['offline_status'] . '=>' . $data['offline_status'] . '];';
            }
            if ($info['staff_id'] != $data['staff_id']) {
                $changeDesc .= '修改销售导购[' . $info['staff_id'] . '=>' . $data['staff_id'] . '];';
            }
            if ($info['add_time'] != $data['add_time']) {
                $changeDesc .= '修改订单日期[' . date('Y-m-d H:i:s', $info['add_time']) . '=>' . date('Y-m-d H:i:s', $data['add_time']) . '];';
            }
            $goods = I('post.goods_id');
            if (!empty($goods)) {
                $arr = array();
                foreach ($goods as $k => $v) {
                    $arr[] = $k;
                }
                $goods_str = implode(',', $arr);
            } else {
                $goods_str = '';
            }
            if ($data['add_time'] == 0) {
                $this->ajaxError("日期错误");
            }
            $where = "order_id = $oid ";
            $ret = M('order_info')->where($where)->save($data);
            $oldArr = M('order_goods')->where($where . " and get_way = 1")->getField('goods_id');
            $oldGoodsStr = implode(',', $oldArr);
            if ($oldGoodsStr != $goods_str) {
                $changeDesc .= '修改取货方式[' . $oldGoodsStr . '=>' . $goods_str . ']';
            }
            if ($ret == 0 && $oldGoodsStr == $goods_str) {
                $this->ajaxError("未更新");
            }
            if (empty($goods_str)) {
                $data2['get_way'] = 0;
                M('order_goods')->where($where)->save($data2);
            } else {
                $data2['get_way'] = 1;
                $data2['depart_id'] = $data['depart_id'];
                $data3['get_way'] = 0;
                $where1 = $where . " and goods_id not in ($goods_str)";
                $where .= " and goods_id in ($goods_str)";
                M('order_goods')->where($where)->save($data2);
                M('order_goods')->where($where1)->save($data3);
            }
            \Com\Order::order_action2($oid, $Info['order_status'], $Info['shipping_status'], $Info['pay_status'], $changeDesc, $userInfo['real_name']);
            \Com\Order::addDeliveryOrder($oid);
            $this->ajaxSuccess("订单更新成功");
        } else {
            $id = I('get.id', 0, 'intval');
            $list = D('Home/OrderDetail')->where("order_goods.order_id = $id")->select();
            $info = $list[0];
            $door = M('user_depart')->select();
            $this->assign('info', $info);
            $this->assign('door', $door);
            $this->assign('list', $list);
            $this->display();
        }
    }

    /**
     * 导购列表
     */
    public function staffList() {
        $id = I('get.id', 0, 'intval');
        $list = M('user_staff')->where("depart_id = $id and is_active = 1")->select();
        $str = '<option value="0">系统销售</option>';
        foreach ($list as $v) {
            $str .= "<option value='" . $v['staff_id'] . "'>" . $v['staff_name'] . "</option>";
        }
        echo $str;
    }

    /**
     * 下载数据
     */
    public function downLoadDetail() {
        $idStr = session('departStr');
        $where = " order_sn > 99999999 and order_info.depart_id in ($idStr)";
        $page = I('post.page', 0, 'intval');
        $buytype = I('post.paytype', 2, 'intval');
        $billtype = I('post.billtype', -1, 'intval');
        $order = I('post.order', 'order_id desc', 'string');
        $stime = strtotime(I('post.start_time', '', 'string'));
        $etime = strtotime(I('post.end_time', '', 'string'));
        $orderSn = I('post.order_sn', '', 'string');
        $buyMan = I('post.buy_name', '', 'string');
        $username = I('post.user_name', 0, 'intval');
        $departId = I('post.sell_depart', 0, 'intval');
        if ($username > 0) {
            $where .= " and user_name = $username ";
        }
        if ($departId > 0 && $departId < 999998) {
            $where .= " and order_info.depart_id = $departId ";
        }
        if ($stime > 0) {
            $where .= " and order_info.add_time >= $stime ";
        }
        if ($etime > 0) {
            $where .= " and order_info.add_time <= $etime ";
        }
        if (!empty($orderSn)) {
            $where .= " and order_sn like '%$orderSn%'";
        }
        if (!empty($buyMan)) {
            $where .= " and consignee like '%$buyMan%'  ";
        }
        if ($buytype > 0) {
            if ($buytype == 1) {
                $where .= " and order_status = 0 ";
            }
            if ($buytype == 2) {
                $where .= " and pay_status = 2 ";
            }
            if ($buytype == 3) {
                $where .= " and pay_status = 2 and shipping_status = 1 ";
            }
            if ($buytype == 4) {
                $where .= " and order_status = 2 ";
            }
            if ($buytype == 5) {
                $where .= " and pay_status = 2 and shipping_status in (3,4,5) ";
            }
            if ($buytype == 6) {
                $where .= " and pay_status = 2 and shipping_status = 2 ";
            }
        }
        if ($billtype >= 0) {
            $where .= " and offline_status = $billtype ";
        }
        Vendor('PHPExcel.PHPExcel');
        $excel  = new \PHPExcel();
        $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O');
        $tableheader = array('类型', '单号', '类别', '商品', '厂家货号', '款号', '规格', '价格', '数量', '店铺', '导购', '品牌', '下单时间','供应商');
        // 填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }
        //表格数组
        $field = 'offline_status,depart_name,staff_name,order_sn,goods_name,supplier_sn,goods_sn,goods_attr,goods_price,goods_number,cat_name,brand_name,add_time,brand_name,suppliers_name';
        $data  = D('Home/OrderDetail')->field($field)->where($where)->select();
        $counts = count($data);
        // 填充表格信息
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $value = $data[$i - 2]['offline_status'];
            $value = $value == 2 ? '线下' : '线上';
            $excel->getActiveSheet()->setCellValue("$letter[0]$i", "$value");
            $value = $data[$i - 2]['order_sn'];
            $excel->getActiveSheet()->setCellValue("$letter[1]$i", "$value");
            $value = $data[$i - 2]['cat_name'];
            $excel->getActiveSheet()->setCellValue("$letter[2]$i", "$value");
            $value = $data[$i - 2]['goods_name'];
            $excel->getActiveSheet()->setCellValue("$letter[3]$i", "$value");
            $value = $data[$i - 2]['supplier_sn'];
            $excel->getActiveSheet()->setCellValue("$letter[4]$i", "$value");
            $value = $data[$i - 2]['goods_sn'];
            $excel->getActiveSheet()->setCellValue("$letter[5]$i", "$value");
            $value = $data[$i - 2]['goods_attr'];
            $excel->getActiveSheet()->setCellValue("$letter[6]$i", "$value");
            $value = $data[$i - 2]['goods_price'];
            $excel->getActiveSheet()->setCellValue("$letter[7]$i", "$value");
            $value = $data[$i - 2]['goods_number'];
            $excel->getActiveSheet()->setCellValue("$letter[8]$i", "$value");
            $value = $data[$i - 2]['depart_name'];
            $excel->getActiveSheet()->setCellValue("$letter[9]$i", "$value");
            $value = $data[$i - 2]['staff_name'];
            $excel->getActiveSheet()->setCellValue("$letter[10]$i", "$value");
            $value = $data[$i - 2]['brand_name'];
            $excel->getActiveSheet()->setCellValue("$letter[11]$i", "$value");
            $value = date('Y/m/d H:i:s', $data[$i - 2]['add_time']);
            $excel->getActiveSheet()->setCellValue("$letter[12]$i", "$value");
            $value = $data[$i - 2]['suppliers_name'];
            $excel->getActiveSheet()->setCellValue("$letter[13]$i", "$value");
        }
        $write = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $random = uniqid();
        $qrfolder = 'Public/download/';
        createFolder($qrfolder);
        $title = 'Public/download/detail_' . $random . '.xls';
        $write->save($title);
        $title = '/download/detail_' . $random . '.xls';
        $this->ajaxSuccess("200", array('content' => $title));
    }

}
